package cn.csq.netty.nio;

import java.io.*;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class NIOFileChannel03 {
    public static void main(String[] args) throws  Exception{
        //使用一个buffer 完成文件拷贝

        //读取
        File file = new File("/Users/csq/Desktop/study/code/netty-study/src/main/resources/fileChannel.txt");
        FileInputStream fileInputStream = new FileInputStream(file);
        FileChannel fileChannel = fileInputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate((int) file.length());
        //文件 -> 输入流 通道 -> 读取到 buffer  buffer 翻转 写入到输出流
        fileChannel.read(byteBuffer);

        String fileString = new String(byteBuffer.array());
        System.out.println("file read String = " + fileString);

        //写入
        byteBuffer.flip();

        FileOutputStream fileOutputStream = new FileOutputStream("/Users/csq/Desktop/study/code/netty-study/src/main/resources/fileChannelOutput.txt");
        FileChannel fileOutputStreamChannel = fileOutputStream.getChannel();

        fileOutputStreamChannel.write(byteBuffer);


        System.out.println("file input");

        fileInputStream.close();
        fileOutputStream.close();



    }
}
